<template>
  <!-- 已采用产品编辑页面 -->
  <view class="create-product h-full flex flex-col box-border">
    <view class="overflow-auto flex-1 p-32rpx text-28rpx" style="min-height: 0;">
      <up-form :labelWidth="70" class="create-product-card-info" :rules="rules" labelPosition="top" :model="formData"
        ref="infoFormRef">
        <up-form-item label="产品名称" prop="productName">
          <up-input disabled v-model="formData.name"></up-input>
        </up-form-item>
        <view>
          <view class="flex justify-between my-10rpx">
            <view class="text-24rpx">产品价格</view>
            <up-icon name="edit-pen" size="20" color="#333" @click="popupPrice = true"></up-icon>
          </view>
          <view class="flex justify-between my-10rpx" v-for="(item, index) in currentRecord.priceInfoDtos" :key="index">
            <view class="text-#6B7280">{{ `${item.productQuality || ''}-${item.minOrder || ''}pcs` }}</view>
            <view>{{ currentRecord.priceInfoDtos[index].currency?.unitSymbol }}{{
              thousandSeparatFormat(formData.priceList[index].productPrice) }}</view>
          </view>
        </view>
        <up-form-item label="产品重量" prop="weight">
          <up-input disabled type="number" v-model="formData.weight" count>
            <template #prefix>g</template>
          </up-input>
        </up-form-item>
        <up-form-item :labelWidth="110" label="商家SKU编码" prop="supplierSkuId">
          <up-input v-model="formData.supplierSkuId"></up-input>
        </up-form-item>
        <view>
          <view class="flex justify-between my-10rpx">
            <view class="text-24rpx">OEM编码</view>
            <up-icon v-if="!currentRecord?.applyOemCodeList?.length" name="plus-circle" size="20" color="#333"
              @click="show = true"></up-icon>
          </view>
          <view v-if="currentRecord?.oemCodeList?.length" class="my-10rpx">
            <view class="text-#6B7280 text-28rpx" v-for="(item, index) in currentRecord.oemCodeList" :key="index">
              {{ item.oemCode }}
            </view>
          </view>
          <view v-if="currentRecord?.applyOemCodeList?.length" class="my-10rpx">
            <view class="text-#6B7280 flex text-28rpx" v-for="(item, index) in currentRecord.applyOemCodeList"
              :key="index">
              <view>{{ item.oemCode }}</view>
              <view class="oemCode text-#FF9A2E ml-16rpx">审核中</view>
            </view>
          </view>
        </view>
        <!-- 新增oem -->
        <view v-if="oemCode.length" class="oem-box" @click="show = true">
          <view class="p-10rpx" v-for="(code, idx) in oemCode" :key="idx">{{ code }}</view>
        </view>
        <up-form-item labelPosition="top" label="物品照片" prop="files">
          <up-upload :fileList="fileList" name="files" multiple :maxCount="3"
            :uploadText="`可上传${3 - fileList.length}张图片`" @afterRead="afterRead" @delete="deletePic" />
        </up-form-item>
      </up-form>
    </view>
    <view class="foot-card flex justify-center items-center w-full h-144rpx p-32rpx box-border">
      <up-button color="#1A5FA9" type="primary" shape="circle" text="保存" @click="editProductSave()"></up-button>
    </view>
  </view>
  <!-- 添加oem编码弹窗 -->
  <up-popup :show="show" @close="show = false" @open="show = true">
    <view class="flex flex-col">
      <view class="p-32rpx">
        <up-form :labelWidth="70" class="oem-form" labelPosition="top" :labelStyle="{ fontWeight: 900 }"
          :model="formData" ref="oemFormRef">
          <up-form-item label="OEM编码" :labelWidth="110" labelPosition="top" prop="oemCode">
            <up-textarea ref="oemRef" v-model="formData.oemCode" :height="88" :maxlength="1500" :focus="isFocus"
              placeholder="请输入，如有多个用逗号隔开"></up-textarea>
          </up-form-item>
        </up-form>
      </view>
      <view class="foot-card flex justify-center items-center w-full h-144rpx p-32rpx box-border">
        <view class="mr-24rpx w-50%">
          <up-button shape="circle" text="取消" @click="cancelOem"></up-button>
        </view>
        <view class="w-50%">
          <up-button color="#1A5FA9" type="primary" shape="circle" text="保存" @click="saveOem()"></up-button>
        </view>
      </view>
    </view>
  </up-popup>
  <!-- 编辑价格弹窗 -->
  <up-popup :show="popupPrice" @close="closePrice" closeable @open="popupPrice = true">
    <view class="create-product flex flex-col max-h-1200rpx">
      <view class="p-32rpx pb-0 font-700 text-36rpx">产品价格</view>
      <view class="p-32rpx pt-0 overflow-auto">
        <up-form :labelWidth="200" class="price-form" labelPosition="top" :labelStyle="{ fontWeight: 900 }"
          :model="formData" ref="priceFormRef">
          <up-form-item v-for="(item, index) in currentRecord.priceInfoDtos" :key="index"
            :class="formData.priceList[index].productPrice > item.prePrice ? 'red-border' : ''"
            :label="`${item.productQuality || ''}-${item.minOrder || ''}pcs`" labelPosition="top"
            :prop="`priceList${index}`">
            <view
              :class="deThousandSeparatFormat(formData.priceList[index].productPrice) > item.prePrice ? 'red-border' : ''">
              <up-input type="number" inputAlign="right" v-model="formData.priceList[index].productPrice"
                placeholder="请输入" count :formatter="(num) => thousandSeparatFormat(num)" @change="priceChange(item)">
                <template #prefix>{{ item.currency?.unitSymbol }}</template>
              </up-input>
              <view v-if="deThousandSeparatFormat(formData.priceList[index].productPrice) > item.prePrice"
                class="text-red-6 text-24rpx">不能高于原来价格</view>
              <view v-if="deThousandSeparatFormat(formData.priceList[index].productPrice).trim() === ''"
                class="text-red-6 text-24rpx">价格不能为空</view>
            </view>
          </up-form-item>
        </up-form>
      </view>
      <view class="foot-card flex justify-center items-center w-full h-144rpx p-32rpx box-border">
        <view class="mr-24rpx w-50%">
          <up-button shape="circle" text="取消" @click="cancelPrice"></up-button>
        </view>
        <view class="w-50%">
          <up-button color="#1A5FA9" type="primary" shape="circle" text="保存" @click="savePrice"></up-button>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<script setup lang="ts">
import { productQueryProductDetailId } from '@/genapi/_productDetail'
import { productManageSupUpdateProductPrice } from '@/genapi/productManageSup'
import { debounce } from '@antfu/utils'
import { handleFile } from "@/api/request"
import { thousandSeparatFormat, deThousandSeparatFormat } from "@/utils/utils";

const infoFormRef = ref()
const priceFormRef = ref()
const show = ref(false)
const popupPrice = ref(false)
const isFocus = ref(false)
const oemCode = ref<string[]>([])
const deleteImgIds = ref<any[]>([])
let productId = ''
let productState = ''
const currentRecord = ref<any>({})
const disabledFlag = ref(false)
const fileList = ref([])
const formData = reactive<any>({
  name: '',
  productPrice: 0,
  priceList: [],
  weight: '',
  oemCode: '',
  supplierSkuId: '',
  files: [] as any,
})

const rules = reactive({
  files:
  {
    validator: (rule: any, value: any, cb: (val?: any) => void) => {
      if (productState !== '0') {
        cb()
        return
      }
      const oemArr = oemCode.value.slice()
      if (!fileList.value.length && !oemArr.concat(currentRecord.value?.oemCodeList || [])) {
        cb(new Error('OEM号和图片至少传一个'))
      }
      else { cb() }
    },
    trigger: ['change', 'blur'],
  }
})
const priceChange = debounce(500, priceChangeFun)
function priceChangeFun(item: any) {
  // 先去掉逗号分隔符
  const price = deThousandSeparatFormat(item.productPrice)
  // 再插入分隔符
  item.productPrice = thousandSeparatFormat(price)
}
// oem修改时图片校验必填
function onVaildFile() {
  if (formData.oemCode) {
    infoFormRef.value.clearValidate('files')
  } else {
    infoFormRef?.value?.validateField('files')
  }
}
function close() {
  show.value = false
  isFocus.value = false
  onVaildFile()
}
// 保存oem
function saveOem() {
  if (formData.oemCode.trim()) {
    const tempArr = formData.oemCode.split(/[,，\n]/g)
    const repeatOemArr: string[] = []
    const oemArr: string[] = []
    const oriOemArr = currentRecord.value?.applyOemCodeList?.length && currentRecord.value?.applyOemCodeList.map(item => item.oemCode) || []
    tempArr.forEach((item: string) => {
      if (oemArr.concat(oriOemArr).includes(item)) {
        if (!repeatOemArr.includes(item)) {
          repeatOemArr.push(item)
        }
      } else
        oemArr.push(item)
      return item
    })
    if (oemArr.length > 20) {
      uni.showToast({
        title: '新增oem编码不能超过20条!',
        icon: 'none'
      })
      return
    } else if (repeatOemArr.length) {
      uni.showToast({
        title: `${repeatOemArr.join()}OEM重复，已自动去重`,
        icon: 'none'
      })
      formData.oemCode = oemArr.join()
    }
    oemCode.value = oemArr
  } else {
    oemCode.value = []
  }
  close()
}
// 取消输入oem
function cancelPrice() {
  closePrice()
}
function closePrice() {
  popupPrice.value = false
  currentRecord.value.priceInfoDtos.map(item => {
    item.productPrice = item.prePrice
  })
}
// 保存oem
function savePrice() {
  let flag = true
  if (currentRecord.value.priceInfoDtos.length) {
    flag = currentRecord.value.priceInfoDtos.some(item => item.productPrice > item.prePrice || item.productPrice === '')
  }
  popupPrice.value = flag
}
// 取消输入oem
function cancelOem() {
  formData.oemCode = oemCode.value.join()
  close()
}
// 删除文件
async function deletePic(res: any) {
  fileList.value.splice(res.index, 1)
  infoFormRef?.value?.validateField('files')
  infoFormRef?.value?.validateField('oemCode')
  if (res.file?.id) {
    deleteImgIds.value.push(res.file?.id)
  }
}
const uploadFilePromise = async (url: string) => {
  const uploadPromise = await new Promise(async (resolve, reject) => {
    await uni.uploadFile({
      url: `${import.meta.env.VITE_BASE_API_URL}/api/productManageSup/uploadProductFile`,
      filePath: url,
      name: 'files',
      header: {
        Authorization: 'Bearer ' + uni.getStorageSync('token')
      },
      formData: {
        id: currentRecord.value.id
      },
      success: (res) => {
        resolve(res.data || true)
      },
      fail: (res) => {
        uni.showToast({
          title: '上传失败！',
          icon: 'none'
        })
        reject(res)
      }
    })
    // await new Promise((resolve) => setTimeout(resolve, 800))
    // resolve(result)
  })
  return uploadPromise
}

// 保存成功回调
function successCalback() {
  infoFormRef?.value?.resetFields()
  infoFormRef?.value?.resetFields()
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  })
  uni.switchTab({
    url: '/pages/index/index'
  })
}
async function afterRead(event: any) {
  const photos: any = handleFile(event)
  fileList.value = fileList.value.concat(photos)
  if (fileList.value.length) {
    infoFormRef.value.clearValidate('files')
    infoFormRef.value.clearValidate('oemCode')
  }
}
async function editProduct() {
  const isAddPicture = fileList.value.length && fileList.value.some(item => !(item?.id))
  Promise.all([infoFormRef.value.validate()]).then(async (results) => {
    const [vaild1] = results
    if (vaild1 === true) {
      let params: any = {}
      let priceArr = [...formData.priceList]
      priceArr = priceArr.map(item => {
        item.productPrice = deThousandSeparatFormat(item.productPrice)
        return item
      })
      // 已生成sku 保存商品信息，拿到id
      params = {
        id: productId,
        priceList: priceArr,
        applyOemCodeList: oemCode.value,
        supplierSkuId: formData.supplierSkuId
      }
      if (deleteImgIds.value.length) {
        params.deleteImgIds = deleteImgIds.value.join()
      }
      const { data } = await productManageSupUpdateProductPrice(params)
      if (data?.code === 200 && !isAddPicture) {
        successCalback()
      }
      if (data?.code !== 200 && data?.msg) {
        uni.showToast({
          title: data?.msg,
        })
        return
      }
      // 上传图片
      if (isAddPicture) {
        let newFiles = fileList.value.filter(e => !e.id) || []
        // 创建图片上传promise
        if (newFiles.length) {
          await Promise.all(newFiles.map(async (e) => {
            const promise = await uploadFilePromise(e.url)
            return promise
          })).then((results) => {
            const success = results.every(item => {
              item = JSON.parse(item)
              return item.code === 200
            })
            if (success) {
              successCalback()
            }
          }).catch((err: any) => {
            uni.showToast({
              title: '上传失败',
              icon: 'error'
            })
            console.error('上传失败:', err)
          })
        }
      }
    }
  })
    .catch((error) => {
      console.error('保存失败:', error);
    })
}
const editProductSave = debounce(500, editProduct)
async function getProductDetail() {
  const { data } = await productQueryProductDetailId({ id: productId })
  if (data?.code !== 200) return
  else {
    const result = data.data
    productState = result.productState
    // 已生成sku、已合并sku、价格变更禁用
    disabledFlag.value = result.productState === '1' || result.productState === '2' || result.productState === '4'
    currentRecord.value = result
    formData.name = result.name
    formData.weight = result.weight || ''
    result.priceInfoDtos.forEach((item) => {
      item.prePrice = item.productPrice
      item.productPrice = thousandSeparatFormat(item.productPrice)
      formData.priceList.push(item)
    })
    formData.oemCode = result.oemCode
    formData.supplierSkuId = result.supplierSkuId
    if (result?.fileInfos && result?.fileInfos?.length) {
      const arr = []
      result?.fileInfos.forEach((e) => {
        Object.assign(e, { url: e.fileUrl })
        arr.push(e)
      })
      if (arr.length > 3) arr.length = 3
      fileList.value = arr
    }
  }
}
onLoad(async (options) => {
  if (options?.id) {
    productId = options?.id
    await getProductDetail()
  }
})
</script>
<style scoped lang="scss">
.oem-box {
  box-sizing: border-box;
  min-height: 80rpx;
  border: 1px solid #D1D5DB;
  border-radius: 8rpx;
  vertical-align: middle;
  padding: 10rpx;
}
</style>
